package com.sc.admin.core.bo;

import cn.hutool.core.collection.CollectionUtil;
import com.sc.admin.core.dao.SysCompanyMapper;
import com.sc.common.entity.admin.company.SysCompany;
import com.sc.common.exception.BusinessException;
import com.sc.common.util.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class CompanyBo {
    @Autowired
    private SysCompanyMapper sysCompanyMapper;

    /**
     * 根据部门code判断部门是否已经存在
     * @param code
     * @return
     */
    public boolean isExistsByCode(String code){
        SysCompany companySearch = new SysCompany();
        companySearch.setCode(code);
        List<SysCompany> companies = sysCompanyMapper.select(companySearch);
        if(CollectionUtil.isNotEmpty(companies)){
            return true;
        }
        return false;
    }


    public String getCode(){
        long start = System.currentTimeMillis();
        String code = CodeGenerator.genCompanyCode();
        while (isExistsByCode(code)){
            code = CodeGenerator.genCompanyCode();
            long end = System.currentTimeMillis();
            if((end - start) / 1000 > 20){ // 20秒超时设置，防止活锁
                throw new BusinessException("生成部门编码失败");
            }
        }
        return code;
    }
}
